home *** CD-ROM | disk | FTP | other *** search
- Path: news.compuserve.com!newsmaster
- From: <75151.03563@compuserve.com>
- Newsgroups: comp.lang.c++
- Subject: Destructors in Functions
- Date: 26 Jan 1996 02:32:20 GMT
- Organization: CompuServe Incorporated
- Message-ID: <4e9efk$t7e@dub-news-svc-6.compuserve.com>
- NNTP-Posting-Host: dd35-159.compuserve.com
- Content-Type: text/plain
- Content-length: 2204
- X-Newsreader: AIR Mosaic (16-bit) version 3.10.08.25
-
-
- >> If you pass an object to a function, the language makes a bitwise copy
- >> of it, local to the function (Assuming no copy contructor is defined).
- >> Then, on the way out, the objects destructor is called.
- >>
- >> This will cause problems if the object has any pointers in it (if they
- >> are relased by the destructor, as they 'should' be).
- >>
- >> The question is, why call a destructor on an object for which no
- >> contstructor was called ? The compiler has probably put the local
- >> copy on the stack, and could just pop it off on the way out.
- >>
- >> Calling a destructor, automatically, for which no constructor was called
- >> seems to be a non-useful feature. Does anyone know why this was
- >> included in the language definition ?
- >>
-
- First of all, in the example you give, a constructor is called for the object -
- it is just the default copy ctor which is generated by the compiler.
-
- When an object is passed, by value, into a function the compiler makes a
- temporary copy of the object, using the object's copy constructor. If no
- copy ctor was explicitly defined, the compiler will generate one - which will
- be a member-wise copy of the object.
-
- When function is exited, the temporary object goes out of scope, so it's
- destructor is called.
-
- If a class allocates memory, it should follow the "Law of the Big Three".
- Which basically states if you need to write any of a : copy contructor, an
- assignment operator, or a destructor for a class - you really need all three.
-
- If your class allocates memory, it should have a destructor to free this
- memory. It also needs a copy ctor and an assignment operator, so that
- objects of the class can be copied correctly.
-
- In your example function, if the object being passed in conformed to the
- Law of the Big Three, when it is passed in, its copy ctor would be called
- which would allocated and initialize the memory it needed. When the
- function returned, its destructor would be called, which would free the
- memory. Writing a class that allocates memory and does not have a
- dtor, a copy ctor, and an assignment operator, is a surefire recipe for
- disaster.
-
- Hope this helps,
-
- Tom Keane
- 75151, 03563
-
-
-
-
-
-